package exa.unicen.edu.ringo.rmodel.builder.xstream.converter;

import java.util.Enumeration;
import java.util.Hashtable;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import exa.unicen.edu.ringo.rmodel.bean.Configuration;
import exa.unicen.edu.ringo.rmodel.bean.Node;
import exa.unicen.edu.ringo.rmodel.bean.Service;
import exa.unicen.edu.ringo.rmodel.builder.xstream.converter.helper.IConverterHelper;
import exa.unicen.edu.ringo.rmodel.builder.xstream.converter.helper.NodesConverterHelper;
import exa.unicen.edu.ringo.rmodel.builder.xstream.converter.helper.ServicesConverterHelper;



public class ConfigurationConverter implements Converter {

	private Hashtable<String,IConverterHelper> helpers;
	
	public ConfigurationConverter(){
		helpers = new Hashtable<String,IConverterHelper>();
		
		helpers.put(NodesConverterHelper.NAME, new NodesConverterHelper());		
		helpers.put(ServicesConverterHelper.NAME, new ServicesConverterHelper());
	}
	
	public boolean canConvert(Class clazz) {
		return clazz.equals(Configuration.class);
	}

	public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
		Configuration configuration = (Configuration) value;

		for(Enumeration<IConverterHelper> e = helpers.elements(); e.hasMoreElements(); ){
			IConverterHelper helper = e.nextElement();
			
			writer.startNode(helper.name());
			helper.marshal(writer, context, configuration);
			writer.endNode();
		}
		
		
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		Configuration configuration = new Configuration();
		configuration.nodes = new Hashtable<String,Node>();
		configuration.services = new Hashtable<String,Service>();

		while (reader.hasMoreChildren()) {
			reader.moveDown();
			IConverterHelper helper = helpers.get(reader.getNodeName());
			helper.unmarshal(reader,context,configuration);
			reader.moveUp();
		}

		return configuration;
	}

}
